<template>
	<view class="container">
		<view class="header-wrap">
			<view class="header">
				<view class="item" v-for="item in headerList" @click="topBtn(item)">
					<image :src="item.img" />
					<text>{{ item.text }}</text>
				</view>
			</view>
		</view>
		<view class="content-wrap">
			<view class="row-list">
				<view class="row-item" v-for="item1 in contentList">
					<view class="title">{{ item1.title }}</view>
					<view class="col-list">
						<view class="col-item" v-for="item2 in item1.list" @click="bottomDia(item2)">
							<image :src="item2.img" />
							<view class="text">{{ item2.text }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 普通弹窗 -->
		<uni-popup ref="msgPopup" type="center">
			<view class="popup-content">
				<view class="title">
					<uni-icons class="icon" :type="vdata.isSuccess?'checkbox-filled':'info-filled'" size="24"
						:color="vdata.isSuccess?'#24C789':'#FF5A5A'"></uni-icons>
					<text v-if="vdata.scanCodeResult.type === 'goods'">核销{{vdata.isSuccess?'成功':'失败'}}</text>
					<text v-if="vdata.scanCodeResult.type === 'coupon'">激活{{vdata.isSuccess?'成功':'失败'}}</text>
				</view>
				<template v-if="vdata.scanCodeResult.type === 'goods'">
					<text class="content" style="text-align: center;">实物奖品：{{ vdata.scanCodeResult.goodsName }}</text>
					<text class="content"
						:style="vdata.isSuccess?'':vdata.tipColor">{{vdata.isSuccess?'库存剩余：'+vdata.goodsNumber+'个':vdata.tipMsg}}</text>
				</template>
				<template v-if="vdata.scanCodeResult.type === 'coupon'">
					<text class="content" style="text-align: center;">卡券奖品：{{ vdata.scanCodeResult.couponName }}</text>
					<text v-if="!vdata.isSuccess" class="content" :style="vdata.tipColor">{{ vdata.tipMsg }}</text>
				</template>
				<text class="but" @click="onClose()">我知道了</text>
			</view>
		</uni-popup>
		<!-- 扫码提示语弹框 -->
		<uni-popup ref="tipPopup" type="center" :mask-click="false">
			<view class="popup-content">
				<view class="title">
					<uni-icons class="icon" type="info-filled" size="24" color="#FF5A5A"></uni-icons>
					<text>激活提示</text>
				</view>
				<text class="content">{{ vdata.activeTip }}</text>
				<view style="width: 100%; display: flex; padding: 0 40rpx; box-sizing: border-box; gap: 40rpx;">
					<text class="but" style="background-color: #FF5A5A;" @click="()=>{ tipPopup.close() }">取消</text>
					<text class="but" @click="onActive()">确认激活</text>
				</view>
			</view>
		</uni-popup>
		<!-- 同主体派券 引导用户授权 二维码 -->
		<uni-popup ref="qrCodePopup" type="center" :safe-area="false">
			<view class="popup-container">
				<image :src="vdata.activityQrcodeImg" mode="aspectFit"></image>
				<view>当前客户未授权，请客户扫码后，重新激活</view>
			</view>
		</uni-popup>

		<!-- receiptInformation -->
		<!-- 填写回执信息 -->
		<ReceiptInformation ref="receiptInformationRef" v-model:value="inputData" :receipt-type="vdata.scanCodeResult.receiptType" :receipt-content="vdata.scanCodeResult.receiptContent" @complete="complete"/>
	</view>
</template>

<script setup>
	import { reactive, ref, getCurrentInstance, nextTick, computed } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	// import {  } from '@/http/apiManager.js '
	import { $destoryAward, $activityCoupon, $getActiveTip, } from '@/http/marketing/apiMarketing.js'
	import storageManage from '@/util/storageManage.js'
	import { $awardDetail, } from '@/http/apiManager.js'

	import ReceiptInformation from '@/marketing/index/components/ReceiptInformation.vue'

	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties

	// 消息弹窗
	const msgPopup = ref()
	const tipPopup = ref()
	const receiptInformationRef = ref()
	// 引导支付授权弹窗
	const qrCodePopup = ref()
	// 商户资产提升
	// 资产提升区间弹窗
	const assetRangePopup = ref(null)
	
	

	const vdata = reactive({
		isSuccess: false,
		goodsName: '',
		goodsNumber: '', // 剩余数量
		tipColor: 'color:#FF5A5A',
		tipMsg: '', // 核销失败错误信息
		scanCodeResult: {}, // 扫码结果
		activeTip: '', // 激活提示语
		fansAwardId: '',
		activityQrcodeImg: '', // 扫码派券失败 引导用户授权图片
		isOpenReceipt: 0, // 是否需要回执信息
	})
	
	const headerList = [{
			img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/cd2afd97-701d-4d98-b2eb-324b2447c620.png',
			text: '核销激活',
			func: onScan
		},
		{
			img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/06165aa1-05f4-4c32-9891-f75b25ee41dd.png',
			text: '扫码领券',
			url: '/marketing/coupon/activity',
			func: navigateTo
		},
		{
			img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/06165aa1-05f4-4c32-9891-f75b25ee41dd.png',
			text: '扫码派券',
			url: '/marketing/issueCoupon/issueCoupon',
			func: navigateTo
		},
	]
	
	const contentList = [{
		title: '查询工具',
		list: [
			// { text: '卡券发放记录', img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/de697c34-8290-4992-9226-551551c6243a.png', url: '/marketing/coupon/history', func: navigateTo },
			// { text: '实物核销记录', img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/79f8eb17-5cdc-48cd-a9fe-62a2490bde0f.png', url: '/marketing/goods/history', func: navigateTo },
			{
				text: '客户福分查询',
				img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/ad76aa1b-e4c1-48fa-8df2-8a87d34feaf4.png',
				url: '/marketing/score/index',
				func: navigateTo
			},
			// { text: '客户星级查询', img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/06afd899-ec20-4f4c-a1db-4ab4ae991039.png', url: '/marketing/mchLevel/index', func: navigateTo }
		],
	}, /* {
		title: '商圈配置',
		list: [{
			text: '商圈',
			img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/7b12f6b3-0c17-46b4-b606-17fbe098030f.png',
			url: '/marketing/downtown/index',
			func: navigateTo
		}],
	}, */ {
		title: '营销活动',
		list: [{
				text: '当前活动',
				img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/c3f3ae38-0bbe-446a-93b6-005e4cee06f9.png',
				url: '/marketing/activity/index?flag=0',
				func: navigateTo
			},
			{
				text: '已结束活动',
				img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/f5af66e8-c725-49c6-9713-a2caa9dd5eef.png',
				url: '/marketing/activity/index?flag=1',
				func: navigateTo
			},
			{
				text: '商户活动记录',
				img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/95efc348-4048-45ab-9bd2-a1f06a8f3b39.png',
				url: '/marketing/mchRecord/index',
				func: navigateTo
			}
		],
	}/* ,{
		title: '商家活动',
		list: [{
				text: '审核卡券',
				img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/709e6f23-f96d-4af7-ba9a-7ac4c4b64bb5.png',
				url: '/marketing/mchActivity/audit/index',
				func: navigateTo
			},
			{
				text: '当前活动',
				img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/7ef05143-8cd0-4730-82dc-904ae817afdf.png',
				url: '/marketing/mchActivity/activity/index?state=4',
				func: navigateTo
			},
			{
				text: '已结束活动',
				img: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/cbaf7a24-51b3-4b50-855c-6a9121b371e7.png',
				url: '/marketing/mchActivity/activity/index?state=6',
				func: navigateTo
			}
		],
	} */]

	const inputData = ref()

	// 用户信息
	const khjlAgentNo = storageManage.userInfo().khjlAgentNo

	onShow(() => {
		marketingAbled()
	})
	
	const updateData = ref(0)

	// 确认提交信息
	function complete() {
		// 关闭回执弹窗
		receiptInformationRef.value.close()
		// 卡券走激活 实物走核销
		if(vdata.scanCodeResult.type === 'goods'){
			destoryAward()
		}else{
			uni.showLoading({
				title: '激活中...'
			})
			console.log(inputData.value,'穿给后端的数据')
			// if(inputData.value.deposit){
			// 	updateData.value = (inputData.value.deposit*1).replace(
			// 		/^(-)*(\d+)\.(\d\d).*$/,
			// 		"$1$2.$3"
			// 	);
			// 	// if(inputData.value.deposit*1){
					
			// 	// }
			// 	// {...inputData.value,deposit:},
			// }
			$activityCoupon({
				receiptContent:inputData.value,
				fansAwardId: vdata.scanCodeResult.fansAwardId,
			}).then(() => {
				uni.hideLoading()
				vdata.isSuccess = true
			}).catch(err => {
				vdata.isSuccess = false
				vdata.tipMsg = err
			}).finally(() => {
				onOpen()
			})
		}
	}


	/**
	 * 打开弹窗
	 */
	function onOpen() {
		// vdata.isSuccess = !vdata.isSuccess
		// vdata.goodsName = 'hello'
		msgPopup.value.open();
	}

	/**
	 * 关闭弹窗
	 */
	function onClose() {
		msgPopup.value.close();
	}
	/**
	 * 激活提示弹窗确认按钮
	 */
	function onActive() {
		tipPopup.value.close()
		activityCoupon(vdata.scanCodeResult.fansAwardId)
	}

	/**
	 * 扫码
	 */
	async function onScan() {
		if (!marketingAbled()) return
		uni.scanCode({
			success: async (res) => {
				// 字符串的开头包含了一些不可见的字符，比如不可见的 UTF-8 BOM（字节顺序标记）。使用 trim() 方法去除字符串开头和结尾的空白字符
				try {
					vdata.scanCodeResult = JSON.parse(res.result.trim())
					const { type, fansAwardId, fansId, couponId, goodsId } = vdata.scanCodeResult
					if (type === 'coupon') { // 卡券激活
						
						// 请求卡券详情
						const { bizData:couponDetail } = await $awardDetail({ fansAwardId, couponId })
						const { isOpenReceipt, receiptContent, receiptType } = couponDetail
						vdata.scanCodeResult.isOpenReceipt = isOpenReceipt
						vdata.scanCodeResult.receiptType = receiptType
						if (isOpenReceipt == 1) {
							vdata.scanCodeResult.receiptContent = JSON.parse(receiptContent) // {name:{isMust:true/false},phone:{isMust:true/false}}
							
							console.log(vdata.scanCodeResult.receiptContent,9999999)
							
							// 数据重置
							inputData.value = {
								// 普通回执
								name: '',
								phone: '',
								idCard: '',
								address: '',
								detailAddress: '',
								
								// 开卡\手机银行\提额回执
								bankImg: '',	// 银行卡照片
								bankCard: '',	// 银行卡号
								openDate: '',	// 开卡日期
								depositDate: '',	// 提额日期
								deposit: '',	// 额度
								pension: '',	// 养老金账户号
								mchNo: '',	// 商户号
							}
						}
						uni.showLoading({
							title: '激活中...'
						})
						// 请求激活提示语
						const { code, bizData } = await $getActiveTip({ awardId:couponId, fansId })
						// 发券失败 用户未授权 引导用户
						if (code === 40005) {
							vdata.activityQrcodeImg = 'data:image/png;base64,' + bizData
							qrCodePopup.value.open()
							$infoBox.toast('卡券派送失败')
							return
						}
						if (bizData) { // 如果存在激活提示语 展示激活提示弹窗
							vdata.activeTip = bizData
							uni.hideLoading()
							// 展示激活提示语弹窗
							tipPopup.value.open()
							// receiptInformation.value.open()
						} else { // 如果不存在直接激活卡券
							activityCoupon(fansAwardId)
						}
					} else if (type === 'goods') { // 核销
						// 请求实物详情
						const { bizData:goodsDetail } = await $awardDetail({ fansAwardId, goodsId })
						const { isOpenReceipt, receiptContent, receiptType } = goodsDetail
						vdata.scanCodeResult.isOpenReceipt = isOpenReceipt
						vdata.scanCodeResult.receiptType = receiptType
						if (isOpenReceipt == 1) {	// 如果需要回执的话 直接打开回执信息弹窗 进行信息回填 负责直接核销实物奖品
							vdata.scanCodeResult.receiptContent = JSON.parse(receiptContent) // {name:{isMust:true/false},phone:{isMust:true/false}}
							// 数据重置
							inputData.value = {
								// 普通回执
								name: '',
								phone: '',
								idCard: '',
								address: '',
								detailAddress: '',
								
								// 开卡\手机银行\提额回执
								bankImg: '',	// 银行卡照片
								bankCard: '',	// 银行卡号
								openDate: '',	// 开卡日期
								depositDate: '',	// 提额日期
								deposit: '',	// 额度
								pension: '',	// 养老金账户号
								mchNo: '',	// 商户号
							}
							// 直接打开回执弹窗
							receiptInformationRef.value.show()
							return
						}
						destoryAward()
					} else {
						$infoBox.toast('二维码错误，非核销激活码')
					}

				} catch (e) {
					//TODO handle the exception
					$infoBox.toast(e)
				}

			},
			fail({ errMsg }) {
				if (errMsg.includes('cancel')) {
					$infoBox.toast('取消扫码')
				} else {
					$infoBox.toast('扫码失败，请稍后再试')
				}
			}
		})
	}
	/**
	 * 核销
	 */
	function destoryAward() {
		uni.showLoading({
			title: '核销中...'
		})
		$destoryAward({
			receiptContent: inputData.value,
			fansAwardId: vdata.scanCodeResult.fansAwardId,
			agentNo: khjlAgentNo,
		}).then(({
			bizData
		}) => {
			uni.hideLoading()
			vdata.isSuccess = true
			vdata.goodsNumber = bizData
		}).catch(err => {
			vdata.isSuccess = false
			vdata.tipMsg = err
		}).finally(() => {
			onOpen()
		})
	}
	/**
	 * 激活
	 */
	function activityCoupon(fansAwardId) {
		// 判断是否存在激活回执
		if (vdata.scanCodeResult.isOpenReceipt == 1) {
			receiptInformationRef.value.show() // 打开回执信息弹窗
			return
		}
		uni.showLoading({
			title: '激活中...'
		})
		$activityCoupon({ fansAwardId, agentNo: khjlAgentNo }).then(({ code, bizData }) => {
			uni.hideLoading()
			vdata.isSuccess = true
		}).catch(err => {
			vdata.isSuccess = false
			vdata.tipMsg = err
		}).finally(() => {
			onOpen()
		})
	}
	/**
	 * 路由导航
	 */
	function navigateTo(path){
		if (!marketingAbled()) return
		uni.navigateTo({
			url: path
		})
	}
	/**
	 * 判断当前机构是否可参加营销活动
	 */
	function marketingAbled() {
		return true
		if (khjlAgentNo !== '41000122') {
			$infoBox.toast('功能暂未开放')
			return false
		}
		return true
	}

	// 上方三个按钮
	function topBtn(item) {
		getApp().preventActive(() => {
			item.url ? item.func(item.url) : item.func()
		})

	}

	// 下方
	function bottomDia(item2) {
		console.log('item2item2',item2);
		getApp().preventActive(() => {
			item2.url ? item2.func(item2.url) : item2.func()
		})

	}
</script>

<style lang="less" scoped>
	/deep/.uni-popup .uni-popup__wrapper {
		width: 75% !important;
		padding: 40rpx;
	}

	.popup-container {
		padding: 36rpx;
		box-sizing: border-box;
		background: #fff;
		border-radius: 8rpx;

		image {
			// width: 400rpx;
			// height: 400rpx;
			width: 100%;
		}

		view {
			// width: 400rpx;
			text-align: center;
		}
	}

	.container {
		width: 100%;
		min-height: 100vh;
		overflow: hidden;
		
		.popup-content1{
				width: 600rpx;
				height: 400rpx;
				border-radius: 30rpx;
				background-color: white !important;
				.title1{
					
				}
				.bottomDialog{
					width: 100%;
					height: 100rpx;
					display: flex;
					justify-content: center;
					.btn{
						width: 100rpx;
						height: 60rpx;
						// line-height: 22rpx;
						border-radius: 10rpx;
						font-family: PingFang SC, PingFang SC;
						font-weight: 500;
						font-size: 29rpx;
						color: #FFFFFF;
						
						text-align: center;
					}
				}
			}

		.popContent {
			padding: 40rpx;
			box-sizing: border-box;
			width: 100%;
			background-color: white;

			// display: flex;
			// flex-direction: column;
			// align-items: center;
			// // padding: 40rpx 0rpx;
			// // font-size: 26rpx;
			// background-color: white;
			// border-radius: 20rpx;
			// letter-spacing: 1px;
			// box-sizing: border-box;
			.item {
				display: flex;
				width: 100%;
				height: 50rpx;
				align-items: center;

				.left {
					padding-right: 10rpx;
				}
			}

		}

		.header-wrap {
			width: 100%;
			position: fixed;
			height: 100vh;
			top: 0;
			left: 0;

			.header {
				background: #f5f6fc;
				height: 400rpx;
				display: flex;
				justify-content: space-around;
				align-items: flex-start;
				padding: 60rpx 75rpx 140rpx 60rpx;
				background: linear-gradient(to bottom, #5EA32E, #97fe47);

				.item {
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					gap: 12rpx;

					image {
						width: 100rpx;
						height: 100rpx;
					}

					text {
						font-weight: 400;
						font-size: 26rpx;
						color: #FFFFFF;
						font-style: normal;
						letter-spacing: 2px;
					}
				}
			}
		}

		.content-wrap {
			width: 100%;
			box-sizing: border-box;
			// height: calc( 100vh - 400rpx );
			position: relative;
			z-index: 2;
			margin-top: 400rpx;
			padding: 40rpx;
			background: #fff;
			border-radius: 40rpx 40rpx 0 0;
			box-shadow: 0rpx -10rpx 30rpx -30rpx rgba(0, 0, 0, 0.8);

			.row-list {
				.row-item {
					.title {
						font-weight: bold;
						font-size: 36rpx;
						color: #333333;
						font-style: normal;
					}

					.col-list {
						display: flex;
						// gap:76rpx;
						flex-wrap: wrap;

						.col-item {
							width: 25%;
							margin: 40rpx 0 60rpx;
							display: flex;
							flex-direction: column;
							align-items: center;
							gap: 22rpx;

							.text {
								font-weight: 400;
								font-size: 24rpx;
								color: #333333;
							}
						}
					}
				}
			}

			image {
				width: 110rpx;
				height: 110rpx;
			}
		}

		.popup-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 40rpx 0rpx;
			font-size: 26rpx;
			background-color: white;
			border-radius: 20rpx;
			letter-spacing: 1px;
			box-sizing: border-box;
			// width: 500rpx;

			.title {
				display: flex;
				justify-content: center;
				align-items: center;
				font-weight: bold;
				font-size: 32rpx;
				margin-bottom: 40rpx;
				width: 70%;

				.icon {
					margin-right: 15rpx;
				}
			}

			.content {
				width: 70%;
				margin-bottom: 15rpx;

				.item {
					display: flex;
					height: 80rpx;
					align-items: center;
					border-bottom: 1rpx solid #f0f0f0;

					.left {
						padding-right: 10rpx;
						
						&.require{
							&::before{
								content: '*';
								color: red;
							}
						}
					} 

					.right {
						image {
							width: 120rpx;
							height: 60rpx;
							border-radius: 5rpx;
						}
					}
				}
			}

			.but {
				font-size: 30rpx;
				color: white;
				border-radius: 40rpx;
				width: 80%;
				padding: 18rpx 0rpx;
				background-color: #24C789;
				margin-top: 30rpx;
				text-align: center;
				margin-bottom: 10rpx;
			}

		}

	}
</style>